<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800004 extends BasePay{

    private $appSecret = 'zEwHSIsk6hwSDXW';
    private $appID = '202303081633434227464704000';

    public function order()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
        parent::order();

        $params = Request::instance()->param();
        $json_string = file_get_contents(env('PLATFORM.IDR'));
        $config = json_decode($json_string, true);
        $idr  = $config[$this->order_array['goods_id']];
        if(empty($idr)){
            mylog('计费点对应的印尼金额找不到');
            return false;
        }
        $data = [
            'mchOrderId'=>$this->order_array['id'],
            'amount'=>$idr['Ipay'],
            'currency'=>'IDR',
            'productinfo'=>$idr['Ipay'].' Paket',
            'productTitle'=>'Arcade Rich Fishing - Pack',
            'firstname'=>$this->order_array['userid'],
            'lastname'=>$this->order_array['userid'],
            'callbackUrl'=>'https://pay.carcadefishing.com/home/pay800004/notify',
        ];
        $timestamp = time().'000';
        $str = $this->appID.'api.pay'.'pay'.$timestamp.'SHA512'.json_encode($data,JSON_UNESCAPED_SLASHES).$this->appSecret;
        $sign = hash('sha512', $str);
        // die;
        $header = array('serviceName:api.pay',
                    'method:pay',
                    'mchId:'.$this->appID,
                    'signType:SHA512',
                    'timestamp:'.$timestamp,
                    'sign:'.$sign,
                    'Content-type: application/json'
        );
        // $obj = $this->curl('https://www.tdaypay.com/gateway/base/biz',json_encode($data,JSON_UNESCAPED_SLASHES),$header);
        $obj = $this->curl('https://api.tdaypay.com/gateway/base/biz',json_encode($data,JSON_UNESCAPED_SLASHES),$header);
        $res = json_decode($obj,true);
        if($res['errorCode'] != '000000'){
            return false;
        }
        //保存金额和币种
        (new \app\home\model\TradeLog)->where('id', $this->order_array['id'])->update(['dollPrice'=>$idr['Ipay'],'dollPriceType'=>'IDR']);

        $data_Arr = [
            'code'=>200,
            'msg'=>'success',
            'url'=>$res['data'][0]['checkoutUrl']
        ];
        
        putsuccess($data_Arr);
    }

    public function notify()
    {
        $data = Request::instance()->param();
        mylog($data);
        $header = Request::instance()->header();
        mylog($header);

        try{
            //验证签名
            $str = json_encode($data).$this->appSecret;
            $sign = hash('sha512', $str);

            if($sign != $header['sign']){
                throw new \Exception('sign false');
            }
            if($data['orderStatus'] != 'SUCCESS'){
                throw new \Exception('SUCCESS false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$data['mchOrderId']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            if ($tradeLog){
                $tradeLog->transactionID = $data['orderId'];
                $tradeLog->save();
            }
            if ($tradeLog['dollPrice'] != $data['amount']) {
                throw new \Exception('订单金额不一致' . ' 传参:' .  $data['amount'] . ' 实际:' . $tradeLog['dollPrice']);
            }
            
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800004 订单已经处理过了 订单id".$tradeLog['id']);
                return "success";
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }

            return "success";
        }catch (\Exception $exception){
            mylog('800004-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return 'FAIL';
        }

    }

    
   
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null,$heder)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $heder);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        if ($error = curl_error($ch)) {
            mylog("800003error");
            mylog($error);
            die($error);
        }
        curl_close($ch);
        mylog($response);
        return $response;
    }

   
}
